#testing post commit hooks
from classChatServer import *
#from classDebug import *

class Tank:
	commandA = {}
	parameters = " "
	
	
	def __init__ (self,name="Tank01",port=23000):
		self.commandA["SPEED"] = 0
		self.commandA["DIR"]	= 0
		self.commandA["RAMP"] 	= "off"
		
		self.parameters = "Parameters: "
		for key in self.commandA.keys():
			self.parameters += key+"=XXX, "
		self.parameters = self.parameters[0:-2]
		
		self.breakLoop = False
		self.chatserver = ChatServer(self)
		self.chatserver.main()

		pass
		
	def addSensors(self,theSensor):
		pass
		
	def msg(self,message):
		try:
			self.chatserver.msg(message)
		finally:
			print message
		
	
	def addMotor(self,theMotor,side="left"):
		pass
		
		
	def parseCommand(self,command):
		helpText = 	"Available Commands are: shutdown, restart, help\n"
		#helpText += "speed=XXX, dir=XXX"
		helpText += self.parameters
		command2 = command.upper()
		if command2=="RESTART":
			m = "Restarting Server"
			self.msg(m)
			#self.restart = 1
			self.controlServer("restart")
			#os._exit
		elif command2=="SHUTDOWN":
			m = "Shutting Down Server"
			self.msg(m)
			#self.shutdown = 1
			self.controlServer("shutdown")
			#os._exit
		elif command2=="HELP":
			m = helpText
			self.msg(m)
		elif command2=="EXIT":
			# Client desiring to exit
			m = "Client exiting"
			self.msg(m)
		elif command2=="NOCLIENTS":
			# All Clients disconnected
			m = "Client exiting"
			self.msg(m)
			self.resetTank()
		elif command2=="":
			m = helpText
			self.msg(m)
		elif command.find("=")>-1:
			m = "SET Something"
			cmdA = command2.split("=")
			if (self.setSetPoint(cmdA[0],cmdA[1])==False):
				m = str(cmdA[0])+"="+str(cmdA[1])+" is not a valid setpoint, or not within allowed range."
				self.msg(m)
		else:
			m = "Unknown Command ["+command+"]\n"+helpText
			self.msg(m)
	
	def setSetPoint(self,command,value):
		valid=False
		try:
			if(int(value)):
				# INT BASED COMMAND:
				if (command=="SPEED") and (int(value)>=0 and int(value)<=100):
					valid=True
				elif (command=="DIR") and (int(value)>=0 and int(value)<=100):
					valid=True
		except:
			# String based command
			pass
		
			
		
		if(valid==True):	
			self.commandA[command]=value
		
		return valid

	def controlServer(self,command):
		if command=="restart":
			os._exit(1)
		elif command=="shutdown":
			os._exit(0)

	def resetTank(self):
		m = "Resetting all setpoints."
		self.msg(m)
		for key in self.commandA.keys():
			#print "command: "+str(key)+": "+str(self.commandA[key])+""
			self.commandA["SPEED"]=0
			self.commandA["DIR"]=0
			
		
		